from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response

from celery_tasks.sms.tasks import send_sms_code

"""
前端需要生成一个uuid,传递给我们后台,我们后台生成图片,
把图片验证码内容保存到redis中

1.接收参数
2.生成图片和记录验证码(保存到redis中)
3.返回响应

GET      /verifications/imagecodes/(?P<image_code_id>.+)/


"""
#APIView
#GenericAPIView       对列表和详情视图做了通用支持,一般和mixin配合使用
#ListAPIView,RetriveAPIView
from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection

class RegisterImageCodeView(APIView):

    def get(self,request,image_code_id):

        # 1.生成图片
        text,image = captcha.generate_captcha()

        # 2.记录验证码(保存到redis中)
        redis_conn = get_redis_connection('code')
        from . import constants
        redis_conn.setex('img_%s'%image_code_id,constants.IMAGE_CODE_EXPIRE_TIME,text)

        # 3.返回响应
        return HttpResponse(image,content_type='image/jpeg')

"""
用户在点击获取短信验证码的时候,前端应将手机号,图片验证码内容和uuid传递给后端

1.接收参数
2.校验参数
3.生成短信验证码内容
4.发送短信
5.返回响应

GET     /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx & image_code_id=xxxx

"""
#APIView
#GenericAPIView       对列表和详情视图做了通用支持,一般和mixin配合使用
#ListAPIView,RetriveAPIView
from .serializers import RegisterSmscodeSerializer
from random import randint
from libs.yuntongxun.sms import CCP
class RegisterSmscodeView(APIView):

    def get(self,request,mobile):
        # 1.接收参数
        params = request.query_params
        # 2.校验参数 --->序列化器
        # text = params.get('text')
        # image_code_id = params.get('image_code_id')
        # if not all([text,image_code_id]):
        #     pass
        # else:
        #     pass

        serializer = RegisterSmscodeSerializer(data=params)
        serializer.is_valid(raise_exception=True)

        # 3.生成短信验证码内容
        sms_code = '%06d'%randint(0,999999)

        redis_conn = get_redis_connection('code')
        redis_conn.setex('sms_%s'%mobile,300,sms_code)
        # 4.发送短信
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)

        #delay方法里的参数要和send_sms_code的参数一一对应
        send_sms_code.delay(mobile,sms_code)

        # 5.返回响应
        return Response({'msg':'ok'})





